package com.mobilepay.moneypig.model.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseFragment;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.IncomeListData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.LogDebug;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/8/7 0007
 */

public class PayListFragment extends BaseFragment {
    private static final String TAG = "IncomeListFragment";
    private RecyclerView mDetailRecycle;
    private SmartRefreshLayout mSmartRefresh;
    private IncomeDetailAdapter mIncomeDetailAdapter;
    private static final int MODE_QUERY = 1;
    private static final int MODE_REFRESH = 2;
    private static final int MODE_MORE = 3;

    private static int CURRENT_MODE = 1;

    private int pagesize = 10;
    private int pagenum = 1;
    private int totalPage = -1;
    private List<IncomeListData.DataBeanX.DataBean> dataBeanXList;

    private String type;

    @Override
    protected void onGetArguments(Bundle bundle) {
        type = bundle.getString("income_type", "");
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_income_list);
    }

    @Override
    protected void initViews() {
        mDetailRecycle = (RecyclerView) mLayoutView.findViewById(R.id.income_list_recycle);
        mSmartRefresh = (SmartRefreshLayout) mLayoutView.findViewById(R.id.income_smartrefresh);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setAdapter();
        getPayList();
    }

    private void setAdapter() {
        dataBeanXList = new ArrayList<>();
        mDetailRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
        mIncomeDetailAdapter = new IncomeDetailAdapter(getActivity());
        mIncomeDetailAdapter.setData(dataBeanXList);
        mDetailRecycle.setAdapter(mIncomeDetailAdapter);
    }

    @Override
    protected void onSetListener() {
        mSmartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pagenum = 1;
                CURRENT_MODE = MODE_REFRESH;
                getPayList();
            }
        });
        mSmartRefresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (totalPage != -1 && pagenum < totalPage) {
                    pagenum++;
                    CURRENT_MODE = MODE_MORE;
                    getPayList();
                } else {
                    mSmartRefresh.setEnableLoadmore(false);
                }

            }
        });
        mIncomeDetailAdapter.setOnClickListener(new IncomeDetailAdapter.OnIncomeItemClickListener() {
            @Override
            public void onClick(View v, int position) {
//                startActivity(IncomeDetailActivity.class);
            }
        });
    }

    private void getPayList() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getlist);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("scene_id", "");
        param.add("type", type);
        param.add("page_size", String.valueOf(pagesize));
        param.add("current_page", String.valueOf(pagenum));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getActivity())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(type);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        dataBeanXList.clear();
                        setIncomeListData(jsonString, false);
                    }
                }
                if (totalPage != -1 && pagenum < totalPage) {
                    mSmartRefresh.setEnableLoadmore(true);
                } else {
                    mSmartRefresh.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mSmartRefresh.finishRefresh(false);
                        break;
                    case MODE_MORE:
                        mSmartRefresh.finishLoadmore(false);
                        break;
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                try {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        setIncomeListData(string, true);
                    } else {
                        mSmartRefresh.setEnableLoadmore(false);
                    }
                } catch (Exception e) {
                    LogDebug.e(e);
                    mSmartRefresh.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        mSmartRefresh.finishRefresh(true);
                        break;
                    case MODE_MORE:
                        mSmartRefresh.finishLoadmore(true);
                        break;
                }
                if (totalPage != -1 && pagenum < totalPage) {
                    mSmartRefresh.setEnableLoadmore(true);
                } else {
                    mSmartRefresh.setEnableLoadmore(false);
                }
            }
        });
    }

    /**
     * 设置列表数据
     */
    private void setIncomeListData(String string, boolean save) {
        IncomeListData incomeListData = GsonUtil.GsonToBean(string, IncomeListData.class);
        totalPage = incomeListData.getData().getLast_page();
        List<IncomeListData.DataBeanX.DataBean> dataBeanList = incomeListData.getData().getData();
        if (CURRENT_MODE != MODE_MORE) {
            dataBeanXList.clear();
        }
        if (dataBeanList.size() != 0) {
            dataBeanXList.addAll(dataBeanList);
        } else {
            mSmartRefresh.setEnableLoadmore(false);
        }
        if (save) {
            try {
                String json = GsonUtil.GsonString(dataBeanXList);
                JSONObject jsonObject = new JSONObject(string);
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                JSONArray jsonArray = new JSONArray(json);
                jsonObject1.put("data", jsonArray);
                ACache.get(App.getApp()).put(type, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mIncomeDetailAdapter.setData(dataBeanXList);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mIncomeDetailAdapter.notifyDataSetChanged();
            }
        });
    }

    private static class IncomeDetailAdapter extends RecyclerView.Adapter<IncomeViewHolder> {
        private Context mContext;
        private LayoutInflater mInflater;
        private List<IncomeListData.DataBeanX.DataBean> dataList;

        public IncomeDetailAdapter(Context context) {
            this.mContext = context;
            mInflater = LayoutInflater.from(mContext);
        }

        public void setData(List<IncomeListData.DataBeanX.DataBean> data) {
            this.dataList = data;
        }

        @Override
        public IncomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            return new IncomeViewHolder(mInflater.inflate(R.layout.item_income_list, parent, false));
        }

        @Override
        public void onBindViewHolder(IncomeViewHolder holder, final int position) {
            IncomeListData.DataBeanX.DataBean dataBean = dataList.get(position);
            holder.mTextName.setText(dataBean.getDescribe());
            holder.mTextTime.setText(CommonUtil.formatDate(dataBean.getCreate_time() * 1000, "yyyy-MM-dd"));
            if (dataBean.getType() == 1) {
                holder.mTextMoney.setText("+" + dataBean.getMoney());
            } else {
                holder.mTextMoney.setText("-" + dataBean.getMoney());
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onClick(v, position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }

        public void setOnClickListener(OnIncomeItemClickListener listener) {
            this.mListener = listener;
        }

        OnIncomeItemClickListener mListener;

        interface OnIncomeItemClickListener {
            void onClick(View v, int position);
        }
    }

    static class IncomeViewHolder extends RecyclerView.ViewHolder {
        private TextView mTextName;
        private TextView mTextTime;
        private TextView mTextMoney;

        public IncomeViewHolder(View itemView) {
            super(itemView);
            mTextName = (TextView) itemView.findViewById(R.id.detail_name);
            mTextTime = (TextView) itemView.findViewById(R.id.detail_time);
            mTextMoney = (TextView) itemView.findViewById(R.id.detail_money);
        }
    }

}
